<script setup lang="ts">
import { useUserStore } from '@/stores'
import { dateFormat, getFormatDictMap } from '@/util/dict'
import type { UserInfo } from '@/types/sign'
import { onMounted, ref } from 'vue'
import { deepCopy } from '@/util/token'
import { EditPen, Printer, Close, Upload, icon } from '@/util/icons'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { userUpdatePwd, userUpdateSelf } from '@/api/user'
import { UrlFormat } from '@/util/request'

// 原始用户数据
const userStore = useUserStore()
// 用户信息拷贝数据
const userInfo = ref<UserInfo>({})
function getUserRole() {
  return userStore.roleNames.find((d) => {
    return d.rId == userStore.useRoleId
  })
}
/* 获取对应的字典信息 */
const tableDict = ref<Map<string, string>>()
const sexDict = ref<Map<string, string>>()

onMounted(() => {
  getFormatDictMap('sys_user_manage', 'head').then((d) => {
    tableDict.value = d
  })
  getFormatDictMap('sys_user_sex', 'val').then((d) => {
    sexDict.value = d
  })
})

// 用户信息可编辑控制
const editStatus = ref(false)
// 打开编辑器
function openEdit() {
  editStatus.value = true
  userInfo.value = deepCopy(userStore.info)
}
// 取消编辑
function cancelEdit() {
  editStatus.value = false
  userInfo.value = deepCopy(userStore.info)
}
// 保存编辑
function saveEdit() {
  userUpdateSelf(userInfo.value!)
    .then((d) => {
      ElMessage.success(d.msg)
      editStatus.value = false
      userStore.info = userInfo.value
    })
    .catch((d) => {
      ElMessage.error(d.msg)
    })
}

// 密码修改
const userPwd = ref({ oPwd: '', pwd: '', enter: '' })
const pwdRules = ref<FormRules>({
  oPwd: [
    {
      required: true,
      message: '请输入原密码'
    },
    {
      max: 25,
      min: 8,
      message: '密码的长度应该为8-25个字符',
      trigger: 'change'
    }
  ],
  pwd: [
    {
      required: true,
      message: '请输入新密码'
    },
    {
      max: 25,
      min: 8,
      message: '密码的长度应该为8-25个字符',
      trigger: 'change'
    }
  ],
  enter: [
    {
      required: true,
      message: '请确认新密码'
    },
    {
      trigger: 'change',
      validator(r, v, c) {
        if (v.length < 8 || v.length > 25) {
          c(new Error('密码长度应该为8-25个字符'))
          return
        }
        if (v !== userPwd.value.pwd) {
          c(new Error('与新密码不一致'))
        }
        c()
      }
    }
  ]
})

// 密码表单
const pwdFormRef = ref<FormInstance>()
function uploadPwd() {
  pwdFormRef.value!.validate((d) => {
    if (!d) {
      return
    }
    userUpdatePwd(userPwd.value.oPwd, userPwd.value.pwd)
      .then((d) => {
        ElMessage.success(d.msg)
      })
      .catch((d) => {
        ElMessage.error(d.msg)
      })
  })
}
</script>
<template>
  <div class="page-root user-index-root">
    <el-row :gutter="30">
      <el-col :xl="8" :sm="12">
        <el-card header="个人信息">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <div>
                <el-button v-if="!editStatus" @click="openEdit" :icon="EditPen" text
                  >修改信息</el-button
                >
                <el-button v-if="editStatus" type="info" @click="cancelEdit" :icon="Close" text
                  >取消</el-button
                >
                <el-button v-if="editStatus" type="primary" @click="saveEdit" :icon="Printer" text
                  >保存</el-button
                >
              </div>
            </div>
          </template>
          <el-form :model="userInfo" label-width="100px">
            <el-form-item :label="tableDict?.get('username')"
              ><span>{{ userStore.info?.username }}</span></el-form-item
            >
            <el-form-item :label="tableDict?.get('nickname')"
              ><el-input v-model="userInfo.nickname" v-if="editStatus" />
              <span v-else> {{ userStore.info?.nickname }}</span></el-form-item
            >
            <el-form-item :label="tableDict?.get('sex')"
              ><el-select v-if="editStatus" v-model="userInfo.sex"
                ><el-option
                  v-for="item in sexDict"
                  :value="item[0]"
                  :label="item[1]"
                ></el-option></el-select
              ><span v-else
                >{{ sexDict?.get(userStore.info?.sex!) }}
                <span v-if="userStore.info.sex == '0'" style="color: rgb(254, 98, 233)">♀</span
                ><span style="color: rgb(43, 153, 249)" v-else>♂</span></span
              ></el-form-item
            >
            <el-form-item :label="tableDict?.get('email')"
              ><el-input v-model="userInfo.email" v-if="editStatus" /><span v-else>{{
                userStore.info?.email
              }}</span></el-form-item
            >
            <el-form-item label="角色"
              ><span>{{ getUserRole()?.name }}</span>
            </el-form-item>
            <el-form-item :label="tableDict?.get('phone')"
              ><el-input v-model="userInfo.phone" v-if="editStatus" /><span v-else>{{
                userStore.info?.phone
              }}</span></el-form-item
            >
            <el-form-item :label="tableDict?.get('initTime')"
              ><span>{{ dateFormat(userStore.info?.initTime || '') }}</span></el-form-item
            >
          </el-form>
        </el-card>
      </el-col>
      <el-col :xl="16" :sm="12">
        <el-card>
          <el-tabs type="card">
            <el-tab-pane label="头像">
              <el-row justify="center"
                ><el-avatar
                  class="user-head"
                  :icon="(icon as any)[userStore.info?.head!]"
                  :src="UrlFormat(userStore.info?.head!)"
                ></el-avatar
              ></el-row>
              <el-row justify="center"
                ><el-button class="button" :icon="Upload" type="primary"
                  >上传新头像</el-button
                ></el-row
              >
            </el-tab-pane>
            <el-tab-pane label="修改密码">
              <el-row justify="center">
                <el-form
                  ref="pwdFormRef"
                  :rules="pwdRules"
                  class="pwd-form"
                  :model="userPwd"
                  label-width="100px"
                >
                  <el-form-item label="原密码" prop="oPwd">
                    <el-input clearable v-model="userPwd.oPwd" show-password type="password" />
                  </el-form-item>
                  <el-form-item label="新密码" prop="pwd">
                    <el-input
                      clearable
                      @change="userPwd.enter = ''"
                      v-model="userPwd.pwd"
                      show-password
                      type="password"
                    />
                  </el-form-item>
                  <el-form-item label="确认密码" prop="enter">
                    <el-input clearable v-model="userPwd.enter" show-password type="password" />
                  </el-form-item>
                  <el-row justify="center"
                    ><el-button class="button" type="success" @click="uploadPwd"
                      >修改</el-button
                    ></el-row
                  >
                </el-form>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<style scoped>
.label-title {
  display: inline-block;
  width: 100px;
}

span {
  color: rgb(126, 126, 126);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pwd-form {
  width: 300px;
}

.el-card {
  user-select: none;
  -webkit-user-select: none;
}

.user-head {
  width: 300px;
  height: 300px;
}

.button {
  margin-top: 20px;
}
</style>
